<?php

namespace App\Http\Controllers\Advice;

use App\Advice;
use App\Adviser;
use App\AdviserUserRelation;
use App\Http\Controllers\Health\HealthController;
use Illuminate\Support\Facades\Input;
use App\UploadAdvice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\UserController;
use App\Http\Controllers\AutoAdviceController;

class AdviceController extends Controller
{

    private $user;
    /**
     * ArticleController constructor.
     */
    public function __construct()
    {
        $u=new UserController();
        $this->user=$u->getCurrentUser()['name'];
    }

    function getAdviceAll(){
        $advice = array();

        $atemp = Advice::where('user',$this->user)->orderBy('created_at','desc')->paginate(10);
        foreach($atemp as $a){
            $n = array();
            $n['content'] = $a['content'];
            $n['adviser'] = $a['adviser'];
            array_push($advice,$n);
        }
        return $advice;
    }

    function getAdviceAdmin(){
        $advice = array();

        $atemp = Advice::where('user',$this->user)->where('adviser','系统管理员')->orderBy('created_at','desc')->paginate(10);
        foreach($atemp as $a){
            $n = array();
            $n['content'] = $a['content'];
            $n['adviser'] = $a['adviser'];
            array_push($advice,$n);
        }
        return $advice;
    }

    public function getAdviceDoctor(){
        $advice = array();

        $atemp = Advice::where('user',$this->user)->where('adviser','!=','系统管理员')->orderBy('created_at','desc')->paginate(10);
        foreach($atemp as $a){
            $n = array();
            $n['content'] = $a['content'];
            $n['adviser'] = $a['adviser'];
            array_push($advice,$n);
        }
        return $advice;
    }

    public function getAdvice(){
        $type = Input::get('type');
        $u=new UserController();
        $aa = new AutoAdviceController();
        $advice = array();
        if($type==-1){
            $advice = $this->getAdviceAll();
        }else if($type == 1){
            $advice = $this->getAdviceAdmin();
        }else{
            $advice = $this->getAdviceDoctor();
        }

        return response()->json(array(
            'advice' => $advice
        ));
    }
    /**
     * Display a listing of the resource. return user ui
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $advice=Advice::where('user',$this->user)->orderBy('created_at','desc')->paginate(10);
        $u=new UserController();
        foreach($advice as $a){
            $temp = $a['adviser'];
            if($temp=="系统管理员"){
                $temp = "admin";
            }
            $advisers = $u->find($temp);
            $adviser = null;
            foreach($advisers as $temp){
                $adviser = $temp;
            }
            $a['type'] = $adviser['type'];
        }
        return view('advice.index')->with(['name'=>$this->user,'advice'=>$advice]);
    }

    /**
     * Display a listing of the resource. return adviser ui
     *
     * @return \Illuminate\Http\Response
     */
    public function showAdmin()
    {
        $users=AdviserUserRelation::where('adviser',$this->user)->paginate(12);

        return view('admin.advice.index')->with(['name'=>$this->user,"users"=>$users,"i"=>1]);
    }

    public function searchUser($u){
        $users=AdviserUserRelation::where('adviser',$this->user)->where('user','like','%'.$u.'%')->paginate(12);
        if(count($users)==0){
            return view('admin.advice.index')->with(['name'=>$this->user,"users"=>$users,'error'=>'无符合条件的用户']);
        }
        return view('admin.advice.index')->with(['name'=>$this->user,"users"=>$users,"i"=>1]);
    }

    public function getUserHealthData($u)
    {
        if(AdviserUserRelation::where(['adviser'=>$this->user,'user'=>$u])->first()==null)
        {
            abort(404);
        }
        $h=new HealthController();
        $healthData=$h->getAllHealthData($u)->paginate(13);
        return view("admin.advice.userHealthDetail")->with(['name'=>$this->user,"healthData"=>$healthData]);
    }

    public function getUserSportsData($u)
    {
        if(AdviserUserRelation::where(['adviser'=>$this->user,'user'=>$u])->first()==null)
        {
            abort(404);
        }
        $h=new HealthController();
        $healthData=$h->getAllSportsData($u)->paginate(13);
        return view("admin.advice.userSportsDetail")->with(['name'=>$this->user,"healthData"=>$healthData]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($u)
    {
        if(AdviserUserRelation::where(['adviser'=>$this->user,'user'=>$u])->first()==null)
        {
            abort(404);
        }
        return view("admin.advice.create")->with(['name'=>$this->user,]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,$u)
    {
        if(AdviserUserRelation::where(['adviser'=>$this->user,'user'=>$u])->first()==null)
        {
            abort(404);
        }
        $data=$request->all();
        $validator = $this->validator($data);
        if($validator->fails())
        {
            return redirect()->back()->withErrors($validator->getMessageBag());
        }
        Advice::create([
            'adviser'=>$this->user,
            'user'=>$u,
            'content'=>$data['advice']
        ]);

        return redirect($request->url())->with('successMsg','建议创建成功！');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    private function validator(array $data)
    {
        return Validator::make($data, [
            'advice'=>'required'
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * show ui of advice upload
     *
     * @return \Illuminate\Http\Response
     */
    public function showUpload(){
        return view('admin.advice.upload')->with(['name'=>$this->user]);
    }


    /**
     * deal with file upload
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function upload(Request $request){
       $file=$request->file('myfile');
        if($file==null)
        {
            return redirect()->back()->withErrors('no file selected');
        }
        if($file -> isValid()){
            /*
            $extension = $file -> getClientOriginalExtension();//上传文件的后缀
            if($extension!='xml'&&$extension!=''&&$extension!='zip')
            {
                return redirect()->back()->withErrors('support:.xml,.xls,.zip');
            }
            $newName = md5(date('ymdhis')).".".$extension;
            $file->move($this->laravelPath."\\storage\\app\\uploads",$newName);

           return Storage::get("uploads\\$newName");
            */
            $extension = $file -> getClientOriginalExtension();//上传文件的后缀
            if($extension!='xml'&&$extension!=''&&$extension!='zip')
            {
                return redirect()->back()->withErrors('support:.xml,.xls,.zip');
            }
            if($extension=='xml')
            {
                $this->save($file);
               // return redirect()->back()->with('successMsg',"success");
            }

        }else{
            return redirect()->back()->withErrors('file is invalid');
        }
    }



    /**
     * read xml file
     * @param $str
     * @return SimpleXMLElement
     */
    private function readXml($str)
    {
        return simplexml_load_string($str);
    }

    private function save($file)
    {
        //$data=$this->readXml(Storage::get('healthData/example.xml'));

        /*
        UploadAdvice::create([
            'adviser'=>$this->user,
            'content'=>$data->content
        ]);
        */
    }

    /**
     *distribute a doctor and a coach for a user when user get register
     */
    public function distributeAdviser($user)
    {
        if(Adviser::where('type',2)->first()!=null)
        {
            $doctor_min=Adviser::where('type','2')->min('countUsers');
            $doctor=Adviser::where(['countUsers'=>$doctor_min,'type'=>2])->first();
            AdviserUserRelation::create([
                'adviser'=>$doctor['name'],
                'user'=>$user,
            ]);
            $doctor->update(['countUsers'=>$doctor['countUsers']+1]);
            /*
            $coach_min=Adviser::where('type','3')->min('countUsers');
            $coach=Adviser::where(['countUsers'=>$coach_min,'type'=>3])->first();
            AdviserUserRelation::create([
                'adviser'=>$coach['name'],
                'user'=>$user,
            ]);
            $coach->update(['countUsers'=>$coach['countUsers']+1]);
            */
            Advice::create([
                "adviser"=>"系统管理员",
                'user'=>$user,
                'content'=>"$user 你好，系统已经为您分配了一名医生:".$doctor['name'].",他会关注您的健康状况，并及时给您建议。"
            ]);
        }
    }

}
